//
//  BMSPermissionManager.m
//  WDBMS
//
//  Created by YeJary on 2025/5/13.
//

#import "BMSPermissionManager.h"
#import <AdSupport/AdSupport.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <UIKit/UIKit.h>

@interface BMSPermissionManager ()

@property (nonatomic, assign) BOOL hasRequested;
@end

@implementation BMSPermissionManager

+ (instancetype)sharedManager {
    static BMSPermissionManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (void)requestTrackingAuthorizationIfNeeded {
    if (@available(iOS 14, *)) {
        if ([ATTrackingManager trackingAuthorizationStatus] == ATTrackingManagerAuthorizationStatusNotDetermined && !self.hasRequested) {
            self.hasRequested = YES;
            dispatch_async(dispatch_get_main_queue(), ^{
                [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
                    NSLog(@"IDFA 授权状态: %ld", (long)status);
                }];
            });
        }
    }
}

- (void)fetchIdentifiersWithCompletion:(void(^)(NSString * _Nullable idfa, NSString *idfv))completion {
    NSString *idfv = [UIDevice currentDevice].identifierForVendor.UUIDString;

    if (@available(iOS 14, *)) {
        ATTrackingManagerAuthorizationStatus status = [ATTrackingManager trackingAuthorizationStatus];
        if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
            NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
            if (completion) completion(idfa, idfv);
        } else if (status == ATTrackingManagerAuthorizationStatusNotDetermined) {
            [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
                NSString *idfa = nil;
                if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
                    idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (completion) completion(idfa, idfv);
                });
            }];
        } else {
            if (completion) completion(nil, idfv);
        }
    } else {
        if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
            NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
            if (completion) completion(idfa, idfv);
        } else {
            if (completion) completion(nil, idfv);
        }
    }
}

@end

